package com.workspace.chb_website.service;

import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 媒体文件相关服务
 */

@Service
public class MediaService {

    public void getImage(String imgPath, HttpServletResponse response) throws IOException {
        File file = new File(imgPath);
        if (!file.exists()) {
            response.setStatus(404);
            return;
        }

        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        response.setContentType("image/jpeg");
        OutputStream out = response.getOutputStream();
        for (int l = inputStream.read(bytes); l != -1; l = inputStream.read(bytes)) {
            out.write(bytes);
        }
        out.flush();
        out.close();
    }

    /**
     * 通过编号查找真正的名字，例如sort=2返回name=2-地图性能检测小程序
     *
     * @param sort 分类编号
     * @return 分类全称
     */
    public String getSortName(String sort) {
        File file = new File("D:/lsn/chb_resource");
        String[] fileNames = file.list();
        assert fileNames != null;
        for (String name : fileNames) {
            if (Objects.equals(sort, name.substring(0, name.indexOf("-")))) {
                return name;
            }
        }
        return null;
    }

    /**
     * 把原始数组按照sort字段排序
     *
     * @param ori 原始数组
     * @return 排好序的数组
     */
    public List<Map<String, String>> sortImageNames(List<Map<String, String>> ori){
        Map<String, String> temp;
        for (int i = 0; i < ori.size() - 1; i++) {
            for (int j = i + 1; j < ori.size(); j++) {
                if (Integer.parseInt(ori.get(i).get("sort")) > Integer.parseInt(ori.get(j).get("sort"))) { // 交换两数的位置
                    temp = ori.get(i);
                    ori.set(i, ori.get(j));
                    ori.set(j, temp);
                }
            }
        }
        return ori;
    }
}
